package com.easyexcle.demo.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.easyexcle.demo.easyExcel.annotion.ExcelNotation;
import com.easyexcle.demo.easyExcel.annotion.domain.ExcelComment;
import com.easyexcle.demo.easyExcel.style.CommentCellWriteHandler;
import com.easyexcle.demo.easyExcel.style.CustomSheetWriteHandler;
import com.easyexcle.demo.pojo.UnitExcelDownVoOne;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lkz
 * @Title: EasyExcelController
 * @Description: easyexcel控制
 * @Date: 2023/4/18 8:06
 */
@RestController
public class EasyExcelController {


    /**
     * 测试表格下拉框
     */
    @GetMapping("/dropDownBox")
    public void testSheetDropDownBox(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("下拉框模板导出", "UTF-8").replaceAll("\\+","%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
        EasyExcel.write(response.getOutputStream(), UnitExcelDownVoOne.class).sheet("下拉框")
                .registerWriteHandler(new CustomSheetWriteHandler())
                .registerWriteHandler(new CommentCellWriteHandler(getNotationMap(UnitExcelDownVoOne.class)))
                .doWrite(new ArrayList<UnitExcelDownVoOne>());


    }



    /**
     * 获取批注Map
     *
     * @param clazz 类class
     * @return java.util.Map<java.lang.Integer, java.lang.String>
     * @author SunLingDa
     * @date 2022/11/3 13:24
     */
    public static Map<Integer, ExcelComment> getNotationMap(Class<?> clazz) {
        Map<Integer, ExcelComment> notationMap = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(ExcelNotation.class) ) {
                continue;
            }
            ExcelComment excelComment = new ExcelComment();
            ExcelNotation excelNotation = field.getAnnotation(ExcelNotation.class);
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            excelComment.setRemarkValue(excelNotation.value());
            excelComment.setRemarkColumnWide(excelNotation.remarkColumnWide());
            notationMap.put(excelProperty.index(), excelComment);
        }
        return notationMap;
    }








}
